package com.lpwa.web.controller.system;

import java.util.List;

import com.lpwa.common.config.Global;
import com.lpwa.common.core.text.Convert;
import com.lpwa.common.utils.StringUtils;
import com.lpwa.common.utils.file.FileUploadUtils;
import com.lpwa.framework.util.ShiroUtils;
import com.lpwa.system.domain.DeviceModel;
import com.lpwa.system.domain.SysUser;
import com.lpwa.system.mapper.LablePersonMapper;
import com.lpwa.system.service.IDeviceModelService;
import com.lpwa.system.service.IPersonService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.lpwa.common.annotation.Log;
import com.lpwa.common.enums.BusinessType;
import com.lpwa.system.domain.Person;
import com.lpwa.common.core.controller.BaseController;
import com.lpwa.common.core.page.TableDataInfo;
import com.lpwa.common.core.domain.AjaxResult;
import com.lpwa.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 人员 信息操作处理
 * 
 * @author tanmu
 * @date 2019-05-30
 */
@Controller
@RequestMapping("/system/person")
public class PersonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SysProfileController.class);
    private String prefix = "system/person";
	
	@Autowired
	private IPersonService personService;
	@Autowired
	private LablePersonMapper lablePersonMapper;
	@Autowired
	private IDeviceModelService deviceModelService;
	@RequiresPermissions("system:person:view")
	@GetMapping()
	public String person()
	{
	    return prefix + "/person";
	}
	
	/**
	 * 查询人员列表
	 */
	@RequiresPermissions("system:person:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Person person)
	{
		startPage();
        List<Person> list = personService.selectPersonList(person);
        if (!StringUtils.isEmpty(list)){
        	for (Person p :list){
        		String tagId = personService.selectbindLableId(p.getPersonId());
        		p.setTagId(tagId);
			}
		}
		return getDataTable(list);
	}
	
	
	/**
	 * 导出人员列表
	 */
	@RequiresPermissions("system:person:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Person person)
    {
    	List<Person> list = personService.selectPersonList(person);
		if (list.size()>0){
			for (Person p : list){
				List<String> TagList = lablePersonMapper.selectLablePersonListByPersonIds(Convert.toStrArray(p.getPersonId()));
				if (TagList.size()>0){
					//获取人员绑定的标签Id
					String tagId= TagList.get(0);
					p.setTagId(tagId);
					//通过标签ID获取标签的型号和类型
					String code = tagId.substring(8,10);
					DeviceModel deviceModel = deviceModelService.selectDeviceModelByCode(code);
					if (!StringUtils.isNull(deviceModel)){
						p.setModelNumber(deviceModel.getModelNumber());
						p.setModelType(deviceModel.getModelType());
					}

				}
			}
		}
        ExcelUtil<Person> util = new ExcelUtil<Person>(Person.class);
        return util.exportExcel(list, "person");
    }
	@Log(title = "人员管理", businessType = BusinessType.IMPORT)
	@RequiresPermissions("system:person:import")
	@PostMapping("/importData")
	@ResponseBody
	public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
	{
		ExcelUtil<Person> util = new ExcelUtil<Person>(Person.class);
		List<Person> personList = util.importExcel(file.getInputStream());
		String operName = ShiroUtils.getSysUser().getLoginName();
		String message = personService.importPerson(personList, updateSupport, operName);
		return AjaxResult.success(message);
	}
	@RequiresPermissions("system:person:view")
	@GetMapping("/importTemplate")
	@ResponseBody
	public AjaxResult importTemplate()
	{
		ExcelUtil<Person> util = new ExcelUtil<Person>(Person.class);
		return util.importTemplateExcel("人员数据");
	}

	/**
	 * 新增人员
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
		SysUser user = ShiroUtils.getSysUser();
		String maxId = personService.selectMaxPersonId();
		//截取字符串，数字加一自增，然后拼接
		String newId =null;
		if(StringUtils.isEmpty(maxId)){
			newId = "P0001";
		}else {
			String oldId ="1"+maxId.substring(1);
			int num = Integer.parseInt(oldId)+1;
			String newNum = ""+num;
			newId = "P"+newNum.substring(1);
		}
		mmap.put("user", user);
		mmap.put("newId", newId);
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存人员
	 */
	@RequiresPermissions("system:person:add")
	@Log(title = "人员", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Person person)
	{
		String tagId = person.getTagId();
		if (!StringUtils.isEmpty(tagId)){
			person.setTagId(tagId.toLowerCase());
		}
		person.setCreateBy(ShiroUtils.getLoginName());
		return toAjax(personService.insertPerson(person));
	}

	/**
	 * 修改人员
	 */
	@GetMapping("/edit/{personId}")
	public String edit(@PathVariable("personId") String personId, ModelMap mmap)
	{
		Person person = personService.selectPersonById(personId);
		mmap.put("person", person);
	    return prefix + "/edit";
	}
	/**
	 * 查看人员
	 */
	@GetMapping("/details/{personId}")
	public String details(@PathVariable("personId") String personId, ModelMap mmap)
	{
		Person person = personService.selectPersonById(personId);
		mmap.put("person", person);
		return prefix + "/details";
	}
	
	/**
	 * 修改保存人员
	 */
	@RequiresPermissions("system:person:edit")
	@Log(title = "人员", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Person person)
	{
		String tagId = person.getTagId();
		if (!StringUtils.isEmpty(tagId)){
			person.setTagId(tagId.toLowerCase());
		}
		person.setUpdateBy(ShiroUtils.getLoginName());
		return toAjax(personService.updatePerson(person));
	}
	
	/**
	 * 删除人员
	 */
	@RequiresPermissions("system:person:remove")
	@Log(title = "人员", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(personService.deletePersonByIds(ids));
	}
	/**
	 * 上传头像
	 */
//	@GetMapping("/avatar")
//	public String avatar(ModelMap mmap)
//	{
//		SysUser user = ShiroUtils.getSysUser();
//		mmap.put("user", user);
//		return "/system/person/avatar";
//	}
	/**
	 * 上传图片，返回图片路径
	 */
	@Log(title = "个人信息", businessType = BusinessType.UPDATE)
	@PostMapping("/updateAvatar")
	@ResponseBody
	public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile file)
	{
		try
		{
			if (!file.isEmpty())
			{
				String avatar = FileUploadUtils.upload(Global.getAvatarPath(), file);
				if (!avatar.isEmpty())
				{
					return AjaxResult.success(avatar);
				}
			}
			return error();
		}
		catch (Exception e)
		{
			log.error("修改头像失败！", e);
			return error(e.getMessage());
		}
	}
	/**
	 * 通过代号modelCode查询设备型号
	 */
	@PostMapping("/checkTagId")
	@ResponseBody
	public String checkTagId(Person person)
	{
		String tagid = person.getTagId();
		String code = "";
		if (!StringUtils.isEmpty(tagid)){
			if (tagid.length()>=10){
				code = tagid.substring(8,10);
				DeviceModel deviceModel = deviceModelService.selectDeviceModelByCode(code);
				if (!StringUtils.isNull(deviceModel)){
					return "0";
				}
			}
		}
		return "1";
//		DeviceModel deviceModel = deviceModelService.selectDeviceModelByCode(modelCode);

	}
	@PostMapping("/getTagIdByPersonId")
	@ResponseBody
	public AjaxResult getTagIdByPersonId(@RequestParam String personId){
		return  AjaxResult.success(personService.selectbindLableId(personId));
	}

}
